<?php
/**
 * Created by PhpStorm.
 * User: kevin
 * Date: 2015/7/1
 * Time: 11:41
 */
namespace Api\Department\Model;
use Think\Model;
class DepartmentModel extends Model{
//    protected $tablePrefix = 'k_';
//    protected $connection = UC_DB_DSN;

    protected $_validate = array(
        /* 验证机构名称 */
        array('name', '', -3, self::EXISTS_VALIDATE, 'unique'), //用户名被占用
        array('name', '1,255', -12, self::EXISTS_VALIDATE, 'length'), //机构名称长度不合法
        /* 验证邮箱 */
        array('email', 'email', -5, self::EXISTS_VALIDATE), //邮箱格式不正确
        array('email', '1,32', -6, self::EXISTS_VALIDATE, 'length'), //邮箱长度不合法
        array('email', '', -8, self::EXISTS_VALIDATE, 'unique'), //邮箱被占用
//        array('address', '1,255', -13, self::EXISTS_VALIDATE, 'length'), //地址长度不合法
//        array('tel','/^(0|86|17951)?(13[0-9]|15[012356789]|18[0-9]|14[57])[0-9]{8}$/',-9,self::EXISTS_VALIDATE),//手机号码不合法
        array('username', '1,16', -1, self::EXISTS_VALIDATE, 'length'), //机构名称长度不合法
        array('username', '', -2, self::EXISTS_VALIDATE, 'unique'), //用户名被占用

    );

    protected $_auto = array(
        array('categoryid','arr2str',self::MODEL_BOTH,'function'),
        array('categoryid',null,self::MODEL_BOTH,'ignore'),
    );

    //添加机构
    public function register($data){
        if($this->create($data)){
            if($data['typeid'] == 2 && $data['unit'] == ''){
                return -14;
            }
            if(!isset($data['categoryid'])){  //查新范围
                return -15;
            }
            $uid = $this->add();
            return $uid?$uid:0;
        }else{
            return $this->getError();
        }
    }

    //修改机构
    public function update($data){
        $data = $this->create($data);
        if($data){
            if($data['typeid'] == 2 && $data['unit'] == ''){
                return -14;
            }
            $res = $this->where('id='.$data['id'])->save();
            if($res){
                return  true;
            }else{
                return false;
            }
        }else{
            return $this->getError();
        }
    }

    public function info($id, $field = true){
        $map = array();
        if(is_numeric($id)){
            $map['id'] = $id;
        }else{
            $map['name'] = $id;
        }
        return $this->field($field)->where($map)->find();
    }

    public function audit($id){
        $data['status'] = 1;
        $map['id'] = $id;
        return $this->where($map)->save($data);
    }

    public function getInfo($id){
        $map['id'] = $id;
        return $this->where($map)->find();
    }

    protected function checkDenyEmail($email){
        return true;
    }

    protected function _after_find(&$data, $options){
        if(!empty($data['categoryid'])){
            $data['categoryid'] = explode(',',$data['categoryid']);
        }
    }

}